//
//  PostViewController.m
//  ViewPoint
//
//  Created by Demiao Lin on 10/23/08.
//  Copyright 2008 Tsinghua. All rights reserved.
//

#import "PostViewController.h"
#import "NewSMTH.h"

#define INDICATOR_VIEW	        999
#define TOOLBAR_VIEW	        998

#define kleftTransparentView    997
#define krightTransparentView   996
#define kcenterTransparentView  995

@implementation PostView

@synthesize controller;
@synthesize touchType;

//- (void) didMoveToSuperview {
    // this hook method is used to initialize the view; we don't want 
    // any user input to be delivered to the UIWebView, instead, the 
    // MapView overlay will receive all input and convert it to commands 
    // that can be performed by the Google Maps Javascript API directly
    
    //self.userInteractionEnabled = NO;
//}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /*
    UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Debug 1"
                                                     message:@"Touch in transparent view Began!"
                                                    delegate:nil
                                           cancelButtonTitle:@"Dismiss"
                                           otherButtonTitles:nil] autorelease];
    [alert show];
    
    
    if(self.superview){
        [self.superview touchesBegan:touches withEvent:event];
    }
    */
	touchType = 0;
    self.backgroundColor = [UIColor colorWithHue:0.0 saturation:0.0 brightness:1.0 alpha:0.2];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    self.backgroundColor = [UIColor clearColor];
    if(self.tag==kleftTransparentView){
        if(controller && touchType>=0){
            [controller goToThreadPrevious:nil];
        }
    }else if(self.tag==krightTransparentView){
        if(controller && touchType>=0){
            [controller goToThreadNext:nil];
        }
    }else if(self.tag==kcenterTransparentView){
        if(controller && touchType>=0){
            [controller toggleToolbarAndNavBar];
        }
    }
    /*
    if(self.superview){
        [self.superview touchesEnded:touches withEvent:event];
    }
    */
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    touchType = -1;
	self.backgroundColor = [UIColor clearColor];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	touchType = -1;
	self.backgroundColor = [UIColor clearColor];
	/*
    if(self.superview){
        [self.superview touchesMoved:touches withEvent:event];
	}
	*/
}
    
@end

@implementation PostViewController

@synthesize board;
@synthesize thread_id;
@synthesize post_id;
@synthesize post_type;

@synthesize contentView;
@synthesize webView;
//@synthesize textView;


- (id)init{
	if( (self=[super init]) != nil ){
		smth =[[NewSMTH alloc] init];
	}
	return self;
}

- (id) initWithTitle: (NSString *) title {
	if( (self=[self init]) != nil ){
		[self setTitle: title];
	}
	return self;
}


-(void) loadContentWithURL:(NSString*)url{
	//[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}

-(void) setPostViewWithTitle:(NSString*)title 
					   board:(Board*)b 
					 post_id:(NSInteger*)pid 
				   post_type:(NSString*)type{
	[self setTitle:title];
    //self.navigationController.navigationBar.title = title;
	[self setBoard:b];
	[self setPost_id:pid];
	[self setPost_type:type];
}

-(void) setPostViewWithPostId:(NSInteger*)pid 
					post_type:(NSString*)type{
	[self setPost_id: pid];
	[self setPost_type: type];
}

-(void) setPostViewWithThreadId:(NSInteger*)tid
						post_id:(NSInteger*)pid 
					  post_type:(NSString*)type{
	[self setThread_id: tid];
    [self setPost_id: pid];
	[self setPost_type: type];
}

-(void) setViewWithTitle:(NSString*)title 
				   board:(Board*)b{
	[self setTitle: title];
    //self.navigationController.navigationBar.title = title;
	[self setBoard: b];
}

// Implement loadView to create a view hierarchy programmatically.
- (void)loadView {
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
	CGRect rect = [[UIScreen mainScreen] applicationFrame];
	
	contentView = [[[UIView alloc] initWithFrame:rect] autorelease];
	//contentView.backgroundColor = [UIColor blackColor];
	contentView.autoresizesSubviews = YES;
	contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
	contentView.multipleTouchEnabled = YES;
    
    //self.multipleTouchEnabled = YES;
    //self.navigationController.navigationBar.
    
	webView = [[[UIWebView alloc] initWithFrame:rect] autorelease];
	webView.backgroundColor = [UIColor blackColor];
    
    webView.multipleTouchEnabled = YES;
    webView.exclusiveTouch = NO;
    [webView setUserInteractionEnabled:YES];
    
    //webView.scalesPageToFit = YES;
    contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	[contentView addSubview:webView];
	//[webView loadHTMLString:@"<html><body style='background-color: #222;'></body></html>" baseURL:[NSURL URLWithString:@"http://ipsmth.appspot.com/vp/"]];
    
    PostView *leftTransparentView = [[[PostView alloc] initWithFrame:rect] autorelease];
    leftTransparentView.controller = self;
    leftTransparentView.tag = kleftTransparentView;
    //leftTransparentView.backgroundColor = [UIColor orangeColor];
    [leftTransparentView setUserInteractionEnabled:YES];
    [contentView addSubview:leftTransparentView];
    
    PostView *rightTransparentView = [[[PostView alloc] initWithFrame:rect] autorelease];
    rightTransparentView.controller = self;
    rightTransparentView.tag = krightTransparentView;
    //rightTransparentView.backgroundColor = [UIColor orangeColor];
    [rightTransparentView setUserInteractionEnabled:YES];
    [contentView addSubview:rightTransparentView];
    
    PostView *centerTransparentView = [[[PostView alloc] initWithFrame:rect] autorelease];
    centerTransparentView.controller = self;
    centerTransparentView.tag = kcenterTransparentView;
    //centerTransparentView.backgroundColor = [UIColor orangeColor];
    [centerTransparentView setUserInteractionEnabled:YES];
    [contentView addSubview:centerTransparentView];
    
	/*
	rect.origin.x = rect.origin.y = 0.0f;
	textView = [[UITextView alloc] initWithFrame:rect];
	
	textView.editable = NO;
	textView.textAlignment = UITextAlignmentLeft;
	textView.font = [UIFont fontWithName:@"American Typewriter" size:20];
	textView.backgroundColor = [UIColor whiteColor];
	
	[contentView addSubview:textView];
	[textView release];
	*/
    
	
	self.view = contentView;
	
	[self loadToolbar];

    rect = [[UIScreen mainScreen] applicationFrame];
	UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
	[activityIndicator setCenter:CGPointMake(rect.size.width/2, rect.size.height/2-20)];
    [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
	activityIndicator.tag = INDICATOR_VIEW;
    [self.view addSubview:activityIndicator];
    [activityIndicator startAnimating];
	[activityIndicator release];
    
	//self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    [self setViewsRotation];

	[pool release];
}

- (void)loadToolbar {
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
    NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:9];
	
	UIBarButtonItem *flexibleSpaceItem;
    
    /*
	flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil 
                                                                       action:NULL] autorelease];	
	[buttons addObject:flexibleSpaceItem];
	[flexibleSpaceItem release];
	*/
	 
	UIBarButtonItem *item;
	item = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"up.png"]
                                             style:UIBarButtonItemStylePlain 
                                            target:self 
                                            action:@selector(goToPrevious:)] autorelease];
	item.tag = kpostPrevious;
	[buttons addObject:item];
	
    flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil 
                                                                       action:NULL] autorelease];	
	[buttons addObject:flexibleSpaceItem];
    
	item = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"down.png"]
                                             style:UIBarButtonItemStylePlain 
                                            target:self 
                                            action:@selector(goToNext:)] autorelease];
	item.tag = kpostNext;
	[buttons addObject:item];
	
    flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil 
                                                                       action:NULL] autorelease];	
	[buttons addObject:flexibleSpaceItem];
    
    item = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"FirstThread.png"]
                                             style:UIBarButtonItemStylePlain 
                                            target:self 
                                            action:@selector(goToFirstThread:)] autorelease];
	item.tag = kfirstThread;
	[buttons addObject:item];
	
    flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil 
                                                                       action:NULL] autorelease];	
	[buttons addObject:flexibleSpaceItem];
    
	item = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"LeftArrow.png"]
                                             style:UIBarButtonItemStylePlain 
                                            target:self 
                                            action:@selector(goToThreadPrevious:)] autorelease];
	item.tag = kthreadPrevious;
	[buttons addObject:item];
	
    flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil 
                                                                       action:NULL] autorelease];	
	[buttons addObject:flexibleSpaceItem];
    
	item = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"RightArrow.png"]
                                             style:UIBarButtonItemStylePlain 
                                            target:self 
                                            action:@selector(goToThreadNext:)] autorelease];
	item.tag = kthreadNext;
	[buttons addObject:item];

	/*
	flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil 
                                                                       action:NULL] autorelease];	
	[buttons addObject:flexibleSpaceItem];
	*/
	
    CGRect rect = [[UIScreen mainScreen] applicationFrame];
	UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:rect];
	//toolbar.barStyle = UIBarStyleBlackOpaque;
    toolbar.barStyle = UIBarStyleBlackTranslucent;
	[toolbar setItems:buttons animated:YES];
    [buttons release];
    toolbar.tag = TOOLBAR_VIEW;
	//[toolbar sizeToFit];
    
	//self.navigationItem.titleView = toolbar;
    [contentView setUserInteractionEnabled:YES];
	[contentView addSubview:toolbar];
    [toolbar release];
	
	[pool release];
}

-(void) toggleToolbarItemsEnabled {
	UIToolbar *toolbar = (UIToolbar*)[self.view viewWithTag:TOOLBAR_VIEW];
	UIBarButtonItem *item;
	item = (UIBarButtonItem*)[toolbar viewWithTag:kpostPrevious];
	item.enabled = !item.enabled;
	item = (UIBarButtonItem*)[toolbar viewWithTag:kpostNext];
	item.enabled = !item.enabled;
	item = (UIBarButtonItem*)[toolbar viewWithTag:kfirstThread];
	item.enabled = !item.enabled;
	item = (UIBarButtonItem*)[toolbar viewWithTag:kthreadPrevious];
	item.enabled = !item.enabled;
	item = (UIBarButtonItem*)[toolbar viewWithTag:kthreadNext];
	item.enabled = !item.enabled;
}

- (void)viewDidLoad {
    [super viewDidLoad];
	//NSLog(@"post viewDidLoad");
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
    [self setViewsRotation];
    //[self hideToolbarAndNavBar];
    
	//NSLog(@"post viewWillAppear");
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
    [activityIndicator startAnimating];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	//NSLog(@"post viewDidAppear");
    [self loadPostViewAsynchronously];
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	//NSLog(@"post viewWillDisappear");
    [webView loadHTMLString:@"<html><head></head><body></body></html>" baseURL:[NSURL URLWithString:@"http://ipsmth.appspot.com/vp/"]];
}

- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
	//NSLog(@"post viewDidDisappear");
}

-(void) loadPostViewData:(id)object{
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
	//[activityIndicator startAnimating];
	//NSLog(@"post loadPostViewData");
	//NSString *content = [NewSMTH getPostContentFromBoardId:[self.board bid] post_id:self.post_id post_type:self.post_type];
    
    Post *post = [smth getPostWithBoardId:[self.board bid] post_id:self.post_id post_type:self.post_type];
    if(post && ([post pid]!=self.post_id || [post_type isEqualToString:@"no"])){
        [self setPostViewWithThreadId:[post tid] post_id:[post pid] post_type:@"no"];
        [self setTitle:[post title]];
        
		NSString *css = [smth getCssStyle];
		NSString *script = @"<script type='text/javascript'>\nfunction appendToBody(html){var div_node=document.createElement('div');div_node.innerHTML=html;document.body.appendChild(div_node);}\n</script>";
		NSString *html = [NSString stringWithFormat:@"<html><head><style>%@</style>\n%@</head><body><div>%@</div></body></html>", css, script, [post content]];
		//NSString *html = [NSString stringWithFormat:@"<html><head>%@\n%@</head><body><div><div onclick='toggleHead(\"Post_%d\")'><span class='title'>%@</span></div>%@</div></body></html>", css, script, [post pid], [post title], [post content]];
        NSLog(html);
		
        [self.webView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://ipsmth.appspot.com/vp/"]];
        
    }
	[activityIndicator stopAnimating];
	[self toggleToolbarItemsEnabled];
	
    [pool release];
}

-(void) loadPostView{
	//NSLog(@"post loadPostView");
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
	[activityIndicator startAnimating];
	[self loadPostViewData:nil];
    //[self performSelectorInBackground:@selector(loadPostViewData:) withObject:nil];
	//[NSThread detachNewThreadSelector:@selector(loadPostViewData:) toTarget:self withObject:nil];
}

-(void) loadPostViewAsynchronously{
	//NSLog(@"post loadPostViewAsynchronously");
    
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
    [activityIndicator startAnimating];
	//[self loadPostViewData:nil];
    [self performSelectorInBackground:@selector(loadPostViewData:) withObject:nil];
	//[NSThread detachNewThreadSelector:@selector(loadPostViewData:) toTarget:self withObject:nil];
}

-(void) goToPrevious:(id)sender{
	[self toggleToolbarItemsEnabled];
	//item.image=@"";
	[self setPostViewWithPostId:self.post_id post_type:@"previous"];
	[self loadPostViewAsynchronously];
}
-(void) goToNext:(id)sender{
	[self toggleToolbarItemsEnabled];
	[self setPostViewWithPostId:self.post_id post_type:@"next"];
	[self loadPostViewAsynchronously];
}

-(void) goToFirstThread:(id)sender{
    if(self.thread_id != self.post_id){
        [self toggleToolbarItemsEnabled];
        [self setPostViewWithPostId:self.thread_id post_type:@"no"];
        [self loadPostViewAsynchronously];
    }
}
-(void) goToThreadPrevious:(id)sender{
    if(self.thread_id != self.post_id){
        [self toggleToolbarItemsEnabled];
        [self setPostViewWithPostId:self.post_id post_type:@"thread_previous"];
        [self loadPostViewAsynchronously];
    }
}
-(void) goToThreadNext:(id)sender{
	[self toggleToolbarItemsEnabled];
	[self setPostViewWithPostId:self.post_id post_type:@"thread_next"];
	[self loadPostViewAsynchronously];
}

-(void) goToPost:(id)sender{
	NSString *type = @"previous";
	if([type isEqualToString:@"previous"]){
		
	} else if([type isEqualToString:@"next"]){
		
	} else if([type isEqualToString:@"thread_previous"]){
		
	} else if([type isEqualToString:@"thread_next"]){
		
	}
	[self setPostViewWithPostId:self.post_id post_type:type];
	[self loadPostViewAsynchronously];
}

- (void) willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation) fromOrientation duration:(NSTimeInterval) duration{
    [self setViewsRotation];
}

- (void) setViewsRotation {
    UIToolbar *toolbar = (UIToolbar*)[self.view viewWithTag:TOOLBAR_VIEW];
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
    
    PostView *leftTransparentView = (PostView*)[self.view viewWithTag:kleftTransparentView];
    PostView *rightTransparentView = (PostView*)[self.view viewWithTag:krightTransparentView];
    PostView *centerTransparentView = (PostView*)[self.view viewWithTag:kcenterTransparentView];
    
    UIInterfaceOrientation orientation = self.interfaceOrientation;
	if(orientation==UIInterfaceOrientationLandscapeLeft || orientation==UIInterfaceOrientationLandscapeRight){
        //[contentView setFrame:CGRectMake(0.0f, 0.0f, 480.0f, 300.0f)];
        [webView setFrame:CGRectMake(0.0f, 0.0f, 480.0f, 300.0f)];
        [leftTransparentView setFrame:CGRectMake(0.0f, 0.0f, 40.0f, 300.0f)];
        [rightTransparentView setFrame:CGRectMake(440.0f, 0.0f, 40.0f, 300.0f)];
        [centerTransparentView setFrame:CGRectMake(230.0f, 0.0f, 20.0f, 300.0f)];
        [toolbar setFrame:CGRectMake(0.0f, 300.0f-44.0f, 480.0f, 44.0f)];
        [activityIndicator setCenter:CGPointMake(240, 140)];
	}else{
        //[contentView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)];
        [webView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)];
        [leftTransparentView setFrame:CGRectMake(0.0f, 0.0f, 40.0f, 460.0f)];
        [rightTransparentView setFrame:CGRectMake(280.0f, 0.0f, 40.0f, 460.0f)];
        [centerTransparentView setFrame:CGRectMake(150.0f, 0.0f, 20.0f, 460.0f)];
        [toolbar setFrame:CGRectMake(0.0f, 460.0f-44.0f, 320.0f, 44.0f)];
        [activityIndicator setCenter:CGPointMake(160, 220)];
	}
    [self.view bringSubviewToFront: activityIndicator];
    [self.view bringSubviewToFront: centerTransparentView];
    [self.view bringSubviewToFront: toolbar];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return YES;
}


- (void)toggleToolbarAndNavBar {
    UINavigationBar *navBar = self.navigationController.navigationBar;
    navBar.hidden = !navBar.hidden;
    UIToolbar *toolbar = (UIToolbar*)[self.view viewWithTag:TOOLBAR_VIEW];
    toolbar.hidden = !toolbar.hidden;
}

-(void) hideToolbarAndNavBar {
    UINavigationBar *navBar = self.navigationController.navigationBar;
    navBar.hidden = YES;
    UIToolbar *toolbar = (UIToolbar*)[self.view viewWithTag:TOOLBAR_VIEW];
    toolbar.hidden = YES;
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    //PostView *leftTransparentView = (PostView*)[self.view viewWithTag:kleftTransparentView];
    //leftTransparentView.backgroundColor = [UIColor grayColor];
    
    //PostView *rightTransparentView = (PostView*)[self.view viewWithTag:krightTransparentView];
    //rightTransparentView.backgroundColor = [UIColor grayColor];
    
    //PostView *centerTransparentView = (PostView*)[self.view viewWithTag:kcenterTransparentView];
    //centerTransparentView.backgroundColor = [UIColor grayColor];
    
    //UINavigationBar *navBar = self.navigationController.navigationBar;
    //navBar.hidden = !navBar.hidden;
    //UIToolbar *toolbar = (UIToolbar*)[self.view viewWithTag:TOOLBAR_VIEW];
    //toolbar.hidden = !toolbar.hidden;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    //PostView *leftTransparentView = (PostView*)[self.view viewWithTag:kleftTransparentView];
    //leftTransparentView.backgroundColor = [UIColor clearColor];
    
    //PostView *rightTransparentView = (PostView*)[self.view viewWithTag:krightTransparentView];
    //rightTransparentView.backgroundColor = [UIColor clearColor];
    
    //PostView *centerTransparentView = (PostView*)[self.view viewWithTag:kcenterTransparentView];
    //centerTransparentView.backgroundColor = [UIColor clearColor];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)dealloc {
    [contentView release];
    [webView release];
	//[textView release];
    [board release];    
    //[thread_id release];
	//[post_id release];
	[post_type release];
	[smth release];
    [super dealloc];
}


@end
